package controllers;

import java.util.ArrayList;
import java.util.LinkedList;

import org.hibernate.ejb.criteria.Renderable;

import play.data.validation.Required;
import play.mvc.Controller;
import play.mvc.With;

import models.Horse;

@With(Secure.class)
public class Horses extends Controller {

	public static void AddHorse(@Required String Name,@Required String Description,
			@Required String DateOfBirth,@Required String CountryOrigin) {
		
		if (!validation.hasErrors()) {
			ArrayList <Horse> listhorse =(ArrayList) Horse.findAll(); 
		//	System.out.println("xxxxxxxxxxxxxxxxxxxxxxx : " + listhorse.get(0).Name);
			if(listhorse.size()!=0){
			for(int i=0 ;i<listhorse.size();i++)
			{
				if(listhorse.get(i).Name.equalsIgnoreCase(Name))
				{
					flash.error("oops another horse has the same name. please change it");
					render();
				}
				
			}
			}
			LinkedList<String> attributes = new LinkedList();
			attributes.addLast(Name);
			attributes.addLast(Description);
			attributes.addLast(DateOfBirth);
			attributes.addLast(CountryOrigin);
			Horse horse = new Horse(attributes);
			horse.save();
			CreatedHorse(horse);
			

		} else {
		render();
		}
	}

	public static void CreatedHorse(Horse horse) {
		render(horse);
	}

	public static void ViewAllHorses() {
		ArrayList horselist = (ArrayList) Horse.findAll();
		render(horselist);
	}

	public static void ViewHorse(long id) {
		Horse x = Horse.findById(id);
		render(x);
	}

	public static void DeleteHorse(long id) {
		Horse horse = Horse.findById(id);
		horse.delete();
		ViewAllHorses();
	}

	public static void EditHorse(long id) {
		Horse x = Horse.findById(id);
		render(x, id);
	}

	public static void AssignHorse(){
		render();
	}
	public static void Assign(Long userid, Long horseid ){
		
		
	}
	public static void Edit(long id, String Name, String Description,
			String DateOfBirth, String CountryOrigin) {
		if (Name != null) {
			Horse x = Horse.findById(id);
			x.Name = Name;
			x.Description = Description;
			x.DateOfBirth = DateOfBirth;
			x.CountryOrigin = CountryOrigin;
			x.save();
			ViewHorse(id);
		}
		else{
			EditHorse(id);
		}
	}

}
